package org.wattdepot.cli.command;

import java.util.List;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * SourceInfo Class.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 */
public class ListSources extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.3 -Returns a string containing a list of all public sources available on this server.
   * 
   * @param args -
   * @return formatted sources
   */
  public String doCommand(List<String> args) {
    StringBuffer buff = new StringBuffer(255);
    String format = "%1$-15s%2$-15s%3$-100s\n";
    List<Source> sources;
    try {
      sources = client.getSources();
      buff.append(String.format(format, "Name", "Parent", "Description"));
      buff.append(cr);
      String parent = null;
      String last = null;
      for (Source source : sources) {
        last = source.getName().substring(source.getName().length() - 1, source.getName().length());
        if (source.getName().equals("SIM_OAHU_GRID")) {
          parent = "NONE";
        }
        else if (last.matches("\\d")) {
          parent = source.getName().substring(0, source.getName().lastIndexOf('_'));
        }
        else {
          parent = "SIM_OAHU_GRID";
        }
        buff.append(String.format(format, source.getName(), parent, source.getDescription()));
      }
    }
    catch (MiscClientException mce) {
      System.out.println("WattDepot Problem >> org.wattdepot.client.MiscClientException: "
          + "1001: Unexpected end of file from server");
      return errorClient;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (NotAuthorizedException nae) {
      return error401;
    }
    return buff.toString();
  }
}
